package com.chb.config;

import com.chb.common.ResultCode;
import com.chb.dto.ResultDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.util.List;

/**
 * @description:
 * @author: CHB
 * @create: 2021-10-28 14:58
 **/
@Slf4j
@RestControllerAdvice
public class ExceptionControllerAdvice {
    /**
     * @ExceptionHandler 捕获全局异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResultDto<Object> handlerException(Exception ex) {
        log.error("系统异常", ex);
        // 获取异常信息
        return ResultDto.builder()
                .data(null)
                .success(false)
                .code(ResultCode.ERROR.getCode())
                .message(ex.getMessage())
                .build();
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResultDto<Object> handler404Exception(NoHandlerFoundException ex) {
        // 获取异常信息
        return ResultDto.builder()
                .data(null)
                .success(false)
                .code(ResultCode.NO_RESOURCE.getCode())
                .message("方法不存在！请检查请求路径是否在正确")
                .build();
    }

    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResultDto<Object> handlerParamExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult exceptions = e.getBindingResult();
        ResultDto<Object> result = ResultDto.builder()
                .data(null)
                .success(false)
                .code(ResultCode.PARAMETER_ERROR.getCode())
                .build();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                result.setMessage(fieldError.getDefaultMessage());
                return result;
            }
        }
        result.setMessage("请求参数错误");
        return result;
    }
}
